﻿using System.Reflection;
using System.Text;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using Microsoft.EntityFrameworkCore;
using MiniX.API.Filters;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authentication.Cookies;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
    options.SwaggerDoc("v1", new OpenApiInfo
    {
        Version = AppSettingsFilter.GetSetting("Setting:Version"),
        Title = "MiniX API",
        Description = "MiniX",
        // TermsOfService = new Uri("https://www.minix.net.cn/html/terms"),
        Contact = new OpenApiContact
        {
            Name = "隐私条款",
            Url = new Uri("https://www.minix.net.cn/html/contact")
        },
        License = new OpenApiLicense
        {
            Name = "授权说明",
            Url = new Uri("https://www.minix.net.cn/html/license")
        }
    });
    options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "MiniX.API.xml"));
    options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "MiniX.Models.xml"));
});
// 注入全局异常日志服务
builder.Services.AddControllers(option =>
{
    option.Filters.Add(typeof(GlobalExceptionFilter));
});

// 增加Http组件
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

// TOKEN校验
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        ValidAudience = AppSettingsFilter.GetSetting("Authentication:JwtBearer:Audience"),
        ValidIssuer = AppSettingsFilter.GetSetting("Authentication:JwtBearer:Issuer"),
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppSettingsFilter.GetSetting("Authentication:JwtBearer:SecurityKey"))),
    };
});

// 根据环境设定数据库连接
var env = AppSettingsFilter.GetSetting("Setting:Env");
if (builder.Environment.IsProduction())
{
    if (env == "PRO")
    {
        // 开发模式-生产库
        builder.Services.AddDbContext<MiniX.API.Data.MiniXApiContext>(opt => {
            if (AppSettingsFilter.GetSetting("ConnectionStrings:PRO_LOCAL") != null)
            {
                var connection = AppSettingsFilter.GetSetting("ConnectionStrings:PRO_LOCAL");
                var server_version = ServerVersion.AutoDetect(connection);
                opt.UseMySql(connection, server_version);
            }
        });
    }
    else
    {
        // 开发模式-测试库
        builder.Services.AddDbContext<MiniX.API.Data.MiniXApiContext>(opt =>
        {
            if (AppSettingsFilter.GetSetting("ConnectionStrings:TEST_LOCAL") != null)
            {
                var connection = AppSettingsFilter.GetSetting("ConnectionStrings:TEST_LOCAL");
                var server_version = ServerVersion.AutoDetect(connection);
                opt.UseMySql(connection, server_version);
            }
        });
    }
}
else
{
    if (env == "PRO")
    {
        // 生产模式-生产库
        builder.Services.AddDbContext<MiniX.API.Data.MiniXApiContext>(opt => {
            if (AppSettingsFilter.GetSetting("ConnectionStrings:PRO_PUBLIC") != null)
            {
                var connection = AppSettingsFilter.GetSetting("ConnectionStrings:PRO_PUBLIC");
                var server_version = ServerVersion.AutoDetect(connection);
                opt.UseMySql(connection, server_version);
            }
        });
    }
    else
    {
        // 生产模式-测试库
        builder.Services.AddDbContext<MiniX.API.Data.MiniXApiContext>(opt =>
        {
            if (AppSettingsFilter.GetSetting("ConnectionStrings:TEST_PUBLIC") != null)
            {
                var connection = AppSettingsFilter.GetSetting("ConnectionStrings:TEST_PUBLIC");
                var server_version = ServerVersion.AutoDetect(connection);
                opt.UseMySql(connection, server_version);
            }
        });
    }
}

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(options =>
    {
        options.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
        options.RoutePrefix = "minixapi";
    });
}

app.UseHttpsRedirection();

// 处理跨域问题
app.UseCors(builder =>
{
    builder.WithOrigins(new[] {
        "http://localhost:7106",
        "https://localhost:7106",
        "http://localhost:7025",
        "https://localhost:7025",
        "https://www.MiniX.cn",
        "https://gx.xlibrary.org.cn",
        "https://gxm.xlibrary.org.cn" }).AllowAnyHeader().AllowAnyMethod().AllowCredentials();
});

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();

